package com.isyscore.os.metadata.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.isyscore.boot.mqtt.MqttTemplate;
import com.isyscore.boot.mqtt.QoS;
import com.isyscore.boot.mqtt.ReceivedMessage;
import com.isyscore.device.common.util.Joiners;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.metadata.service.impl.TenantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * 租户消息监听器
 *
 * @author wux
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class TenantListener {
    public static final String TENANT_ID = "tenantId";
    private final MqttTemplate mqttTemplate;
    private final TenantService tenantService;
    /**
     * 【应用端】经过规则引擎转发的topic前缀
     */
    public static final String NUP_TOPIC = "nup";

    /**
     * 租户变更：nup/tenant/status
     * 消息体
     */
    public static String tenantChange() {
        return Joiners.SLASH.join(NUP_TOPIC, "tenant", "status");
    }

    @PostConstruct
    void listenerInit() {
        log.info("开始监听租户删除事件");
        mqttTemplate.subscribe(tenantChange(), QoS.AT_LEAST_ONCE, (ReceivedMessage message) -> {
            DatabaseMqData databaseMqData = JsonMapper.fromJson(new String(message.getPayload()), DatabaseMqData.class);
            if (ObjectUtil.isNotNull(databaseMqData) && DatabaseMqData.Operation.DELETE.equals(databaseMqData.getOperation())) {
                HashMap<String, String> tenant = JsonMapper.fromJson(databaseMqData.getData(), HashMap.class);
                if (tenant.containsKey(TENANT_ID)) {
                    String tenantId = tenant.get(TENANT_ID);
                    if (StrUtil.isNotBlank(tenantId)) {
                        log.info("清除{}租户关联信息",tenantId);
                        tenantService.deleteTenant(tenantId);
                    }
                }
            }
            if (ObjectUtil.isNotNull(databaseMqData) && DatabaseMqData.Operation.ADD.equals(databaseMqData.getOperation())) {
                HashMap<String, String> tenant = JsonMapper.fromJson(databaseMqData.getData(), HashMap.class);
                if (tenant.containsKey(TENANT_ID)) {
                    String tenantId = tenant.get(TENANT_ID);
                    if (StrUtil.isNotBlank(tenantId)) {
                        log.info("添加{}租户关联信息",tenantId);
                        tenantService.saveTenant(tenantId);
                    }
                }
            }
        });
    }
}
